package com.example.dubboweb.controller;

import com.wjyxsy.service.IUserService;
import com.wjyxsy.service.IUserService2;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

@RestController
@RequestMapping(value = "/demo")
public class DemoController {

    @Reference(check = false)
    private IUserService userService;

    @Reference(check = false)
    private IUserService2 userService2;

    @RequestMapping(value = "/sayHello")
    public String sayHello(String name, HttpServletRequest request) throws UnknownHostException {
        String userRealIP = getUserRealIP(request);
        RpcContext.getContext().setAttachment("ip", userRealIP);
        return userService.sayHello(name);
    }

    @RequestMapping(value = "/sayHello2")
    public String sayHello2(String name, HttpServletRequest request) throws UnknownHostException {
        String userRealIP = getUserRealIP(request);
        RpcContext.getContext().setAttachment("ip", userRealIP);
        return userService2.sayHello2(name);
    }

    public static String getUserRealIP(HttpServletRequest request) throws UnknownHostException {
        String ip = "";
        if  (request.getHeader("x-forwarded-for") == null)  {
            ip = request.getRemoteAddr();
        }  else  {
            ip = request.getHeader("x-forwarded-for");
        }
        if  ("127.0.0.1".equals(ip))  {
            // 获取本机真正的ip地址
            ip = InetAddress.getLocalHost().getHostAddress();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }
}
